<?php

namespace Cli\Controller;

use \Think\Controller;
use Think\Log;

/**
 * 定时服务
 * @modify trainyao 2016-01-21 创建
 */
class ReportController extends Controller {

    private $financeDir = 'Finance';
    private $roomDir = 'Room';

    protected function _initialize() {
        if (!IS_CLI) {
            exit();
        }
    }

    /**
     * 后台队列服务器启动
     * @modify trainyao 2016-01-29    创建
     */
    public function startOrderChangeTask() {
        $GLOBALS['UCLBRT_PROCESS'] = array();
        global $http;
        $http = new \swoole_http_server(C('TASK_SERVER_IP'), C('TASK_SERVER_PORT'));

        $http->on('start', function ($serv) {
            
        });
        $http->on('close', function ($serv) {
            
        });
        $http->on('shutdown', function ($serv) {
            
        });

        $http->on('request', function ($request, $response) {
            $fileLog = new \Org\Util\FileLog();
            $param = $request->post;
            $hasError = false;
            // 校验身份
            $flag = $param['flag'];
            $time = $param['time'];
            $flags = array('uclbrt', 'smsCard', 'quit');

            if ((time() - $time) > 60 || !in_array($flag, $flags)) {
                $validatePass = false;
            }

            if (!in_array($request->server['remote_addr'], array('127.0.0.1', C('TASK_SERVER_IP'))) || $hasError) {
                $response->end('error');
            } else {
                switch ($flag) {
                    case 'uclbrt':
                        if (empty($GLOBALS['UCLBRT_PROCESS']['orderChange'])) {
                            $process = new \swoole_process('orderChangeTaskCallbackFunction', null);
                            $pid = $process->start();
                            $GLOBALS['UCLBRT_PROCESS']['orderChange'] = array(
                                'id' => $pid,
                                'instance' => $process,
                            );
                        }
                        $GLOBALS['UCLBRT_PROCESS']['orderChange']['instance']->write(json_encode($param));
                        break;
                    case 'smsCard':
                        if (empty($GLOBALS['UCLBRT_PROCESS']['sms'])) {
                            $process = new \swoole_process('getCardTaskCallbackFunction', null);
                            $pid = $process->start();
                            $GLOBALS['UCLBRT_PROCESS']['sms'] = array(
                                'id' => $pid,
                                'instance' => $process,
                            );
                        }
                        $data = json_encode($param);
                        $writeResult = $GLOBALS['UCLBRT_PROCESS']['sms']['instance']->write($data);
                        $fileLog->write("($writeResult) $data", 0, RUNTIME_PATH . "/Statistics/" . date('Y-m-d') . "_writeData.log");
                        break;
                    case 'quit':
                        global $http;
                        $http = $GLOBALS['GLOBALS']['http'];
                        $http->close();
                        $http->shutdown();
                        break;
                }

                $response->end('success');
            }
        });
        $http->start();
    }

    /**
     * TODO 测试函数，待删除
     */
    public function test() {
        /*
          $data = array(
          'new' => array(
          'id' => '1',
          'startdate' => '2016-01-25',
          'realnight' => '1',
          'payment' => '120.00',
          'hotelentity_id' => '6',
          'roominfo_id' => '2'
          ),
          'time' => time(),
          'type' => 0
          );
         */
        $data = array(
            'old' => array(
                0 => array(
                    'id' => '1',
                    'startdate' => '2016-01-25',
                    'checkoutdate' => '2016-01-26',
                    'realnight' => '1',
                    'payment' => '120.00',
                    'hotelentity_id' => '6',
                    'roominfo_id' => '2',
                    'night' => 1
                )
            ),
            'new' => array(
                0 => array(
                    'id' => '1',
                    'startdate' => '2016-01-24',
                    'checkoutdate' => '2016-01-28',
                    'realnight' => '2',
                    'payment' => '220.00',
                    'hotelentity_id' => '6',
                    'roominfo_id' => '2',
                    'night' => 4
                )
            ),
            'time' => time(),
            'type' => 1
        );
        return $data;
    }

    /**
     * 统计日常的房间销售以及入住状态，还有营业收入
     * @modify AmosZhong 2016-01-25
     */
    public function room() {
        // 注意函数当前运行时间是每一天的0分，所以订单查询出来的状态是0分状态
        // 比如：
        // startdate是昨天，状态是退房，表示出售了但是提前走了实住0晚
        // startdate是昨天，状态是取消，表示出售了但是取消订单实住0晚
        // startdate是昨天，状态是支付，表示出售了但是没来入住实住0晚
        // startdate是昨天，状态是入住，表示出售了而且来入住了实住1晚
        $yesterday = date('Y-m-d', strtotime('last day'));
        $yesterdayEnd = date('Y-m-d 23:59:59', strtotime('last day'));
        $querySql = "select id,hotelentity_id,roominfo_id,payment,startdate,night,hour,status from tb_order_room where startdate <= \"{$yesterday}%\"and checkoutdate > \"{$yesterday}%\" and status in (1,2,3,4)";
        $records = M('tb_order_room')->query($querySql);
        if ($records === false) {
            $this->log($this->roomDir, 'order room records found false ');
            exit;
        }

        if (empty($records)) {
            $this->log($this->roomDir, 'order room records not found');
            exit;
        }

        ob_start();
        echo 'INSERT INTO `tb_order_room_report` (`hotelentity_id`, `date`, `roominfo_id`, `price`, `orderroom_id`, `status`) values ';
        foreach ($records as $record) {

            $price = floatval($record['payment']) / intval($record['night']);
            $price = number_format($price, 2, '.', '');

            switch ($record['status']) {
                case '1':
                    echo '(', "'{$record['hotelentity_id']}', '{$yesterday}', '{$record['roominfo_id']}', '{$price}', '{$record['id']}', 0", '),';
                    break;
                case '2':
                    echo '(', "'{$record['hotelentity_id']}', '{$yesterday}', '{$record['roominfo_id']}', '{$price}', '{$record['id']}', 1", '),';
                    break;
                case '3':
                    echo '(', "'{$record['hotelentity_id']}', '{$yesterday}', '{$record['roominfo_id']}', '{$price}', '{$record['id']}', 0", '),';
                    break;
                case '4':
                    echo '(', "'{$record['hotelentity_id']}', '{$yesterday}', '{$record['roominfo_id']}', '{$price}', '{$record['id']}', 0", '),';
                    break;
                default:
// 错误type
                    $this->log($this->roomDir, '错误的订单状态： status =' . $record['status']);
                    break;
            }
        }

        $orderRoomReportSql = ob_get_contents();
        $orderRoomReportSql = chop($orderRoomReportSql, ',');
        ob_end_clean();
        $result = M('tb_order_room_report')->execute($orderRoomReportSql);
        if ($result === false) {
            $this->log($this->roomDir, 'tb_order_room_report insert error');
            exit;
        }
        $this->log($this->roomDir, 'jianyefang run success!');


        $querySql = "select id,hotelentity_id,roominfo_id,payment,startdate,night,hour,status from tb_order_room where startdate >= \"{$yesterday}%\"and checkoutdate <= \"{$yesterdayEnd}%\" and status in (1,2,3,4)";
        $records = M('tb_order_room')->query($querySql);
        if ($records === false) {
            $this->log($this->roomDir, 'order room records found false ');
            exit;
        }

        if (empty($records)) {
            $this->log($this->roomDir, 'order room records not found');
            exit;
        }

        ob_start();
        echo 'INSERT INTO `tb_order_room_report` (`hotelentity_id`, `date`, `roominfo_id`, `price`, `orderroom_id`, `status`, `type`) values ';
        foreach ($records as $record) {

            $price = $record['payment'];

            switch ($record['status']) {
                case '1':
                    echo '(', "'{$record['hotelentity_id']}', '{$yesterday}', '{$record['roominfo_id']}', '{$price}', '{$record['id']}', 0, 1", '),';
                    break;
                case '2':
                    echo '(', "'{$record['hotelentity_id']}', '{$yesterday}', '{$record['roominfo_id']}', '{$price}', '{$record['id']}', 1, 1", '),';
                    break;
                case '3':
                    echo '(', "'{$record['hotelentity_id']}', '{$yesterday}', '{$record['roominfo_id']}', '{$price}', '{$record['id']}', 0, 1", '),';
                    break;
                case '4':
                    echo '(', "'{$record['hotelentity_id']}', '{$yesterday}', '{$record['roominfo_id']}', '{$price}', '{$record['id']}', 0, 1", '),';
                    break;
                default:
// 错误type
                    $this->log($this->roomDir, '错误的订单状态： status =' . $record['status']);
                    break;
            }
        }

        $orderRoomReportSql = ob_get_contents();
        $orderRoomReportSql = chop($orderRoomReportSql, ',');
        ob_end_clean();
        $result = M('tb_order_room_report')->execute($orderRoomReportSql);
        if ($result === false) {
            $this->log($this->roomDir, 'tb_order_room_report insert error');
            exit;
        }
        $this->log($this->roomDir, 'zhongdianfang run success!');

        echo "success";
    }

    /**
     * log工具，记录日志
     * TODO 封装到functions，分log类型，参考PSR-3 log levels
     * @modify AmosZhong 2016-01-23
     */
    private function log($dirName, $message) {
        $absoluteDir = RUNTIME_PATH . '/Statistics/' . $dirName . '/';
        if (!is_dir($absoluteDir)) {
            mkdir($absoluteDir, 0770, true);
        }

        if (!empty($message)) {
            Log::write($message, Log::SQL, '', $absoluteDir . date('y_m_d') . '.log');
        }
    }

    /**
     * 关闭后台队列服务器,cli调用
     * @modify trainyao 2016-01-29    创建
     */
    public function quitQueueServer() {
        // 定义数据类型格式
        $data = array(
            'flag' => 'quit',
            'time' => time()
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'http://' . C('TASK_SERVER_IP') . ':' . C('TASK_SERVER_PORT'));
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);

        if ($result != 'success') {
            echo "failed\n";
        }
        echo "succeed\n";
    }

}
